﻿using System.Configuration;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using System.Collections.Generic;
using System;
using System.Reflection;
using System.Collections;
using System.Data;

namespace SinacorWebTools.ResourceAccess
{
    public abstract class DataAccess
    {
        protected DbConnection conn;

        protected DbConnection CreateConnection()
        {
            OracleDatabase db = new OracleDatabase(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
            return db.CreateConnection();
        }

        protected DbConnection CreateConnectionSinaTools()
        {
            OracleDatabase db = new OracleDatabase(ConfigurationSettings.AppSettings["ConnectionStringSinaTools"].ToString());
            return db.CreateConnection();
        }

        public Entity.SortableList<T> MapDataToBusinessEntityCollection<T>(List<IDataRecord> records) where T : new()
        {
            Type businessEntityType = typeof(T);
            Entity.SortableList<T> entitys = new Entity.SortableList<T>();
            Hashtable hashtable = new Hashtable();
            PropertyInfo[] properties = businessEntityType.GetProperties();

            foreach (PropertyInfo info in properties)
            {
                object[] attributes = info.GetCustomAttributes(typeof(Entity.MapEntityData), false);
                if (attributes.Length > 0)
                {
                    Entity.MapEntityData attribute = (Entity.MapEntityData)attributes[0];
                    hashtable[attribute.GetFieldName()] = info;
                }
            }

            foreach (IDataRecord rc in records)
            {
                T newObject = new T();
                for (int index = 0; index < rc.FieldCount; index++)
                {
                    PropertyInfo info = (PropertyInfo)hashtable[rc.GetName(index).ToUpper()];
                    if ((info != null) && info.CanWrite)
                        info.SetValue(newObject, ConvertPropertyType(rc.GetValue(index), info.PropertyType), null);
                }
                entitys.Add(newObject);
            }
            return entitys;
        }

        private object ConvertPropertyType(object valueField, Type fieldType)
        {
            object ret = null;

            if (fieldType == typeof(int))
                ret = int.Parse(valueField.ToString());
            else if (fieldType == typeof(string))
                ret = valueField.ToString();

            return ret;
        }
    }
}
